package com.gmf.sugar;

import java.awt.AWTEvent;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.sql.DataSource;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gmf.sugar.service.StarterChecker;
import com.gmf.sugar.ui.Workspace;

public class Starter {
	private static final Logger LOGGER = LoggerFactory.getLogger(Starter.class);

	public static void main(String[] args) {
		StarterChecker checker = new StarterChecker();
		if (checker.isAppActive()) {
			LOGGER.error("The application has been started already !");
			System.exit(-1);
		} else {
			EventQueue queue = Toolkit.getDefaultToolkit()
					.getSystemEventQueue();
			queue.push(new EventQueue() {
				protected void dispatchEvent(AWTEvent arg0) {
					try {
						super.dispatchEvent(arg0);
					} catch (Throwable t) {
						StringWriter w = new StringWriter();
						t.printStackTrace(new PrintWriter(w));
						JOptionPane.showMessageDialog(null, w.toString()
								.substring(0, 300), "Error",
								JOptionPane.ERROR_MESSAGE);
						t.printStackTrace();
						System.exit(-1);
					}
				}
			});
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					try {
						Workspace ws = new Workspace(Starter.class);
						ws.setVisible(true);
						DataSource ds = (DataSource) Workspace.CTX.getBean("sugarDB");
						System.out.println("Connection is:"+ds.getConnection());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}

	}
}
